package kku.cs.fgl.gui;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;

public class TEdit extends TComponent {
	private String text="";

	private int maxlength=40;

	public TEdit() {
		this(0, 0,100,24);
	}

	public TEdit(float x, float y) {
		this(x, y,100,24);
	}

	public TEdit(float x, float y, int width, int height) {
		super(x, y, width, height);
		
	}

	public int getMaxlength() {
		return maxlength;
	}

	public String getText() {
		return text;
	}

	public void setMaxlength(int maxlength) {
		this.maxlength = maxlength;
	}

	public void setText(String text) {
		this.text = text;
	}

	@Override
	public void paint(Graphics g) {
		int h = getFont().getLineHeight();
		if(getHeight()<h){
			setHeight(h+4);
		}
		if(getBgColor()!=null){
			  g.setColor(getBgColor());
			  g.fillRect(0,0,getWidth(), getHeight());
		}
		if (isFocus()) {
			g.setColor(getColor().brighter());
		} else {
			g.setColor(getColor());
		}
		g.drawRect(0, 0, getWidth(), getHeight());
		
		int w=0,w2=getWidth()-6;
		if(text!=null){
			String s=text;
			do{
			  w=getFont().getWidth(s);
			  if(w>w2){
				  s=s.substring(1);
			  }
			}while(w>w2);			
			getFont().drawString(2,2,s,getTextColor());
		}
		if (isFocus() && caret) {
			g.setColor(getTextColor());
			g.fillRect(w + 4,2, 2,h);
		}
	}

	private int ctime = 0;

	private boolean caret = false;
    private char lastKey=0;
	@Override
	public void update(int time) {
		if (isFocus()) {
			ctime += time;
			if (ctime > 100) {
				caret = !caret;
				ctime = 0;
			}
		}
		super.update(time);
	}

	@Override
	public void keyPressed(int key, char c) {
		if(text==null)text="";
		if(key==Input.KEY_BACK && text.length()>0){
		  text = text.substring(0,text.length()-1);	
		}else{
		  if(c>=32 && text.length()<maxlength){
		    text = text + c;
		    lastKey=c;
		  }
		}
	}
	
}
